/**
 * 
 */
package org.traffometer.traffosim;

import org.traffometer.common.data.TraffoPacket;
import org.traffometer.traffosim.Config.TransmissionMode;

import java.io.File;
import java.util.List;

/**
 *   Sits between model and view.
 *   Methods represent highest level of abstraction of actions system can take.
 *   Gets commands from view, makes changes to the model.
 *   Does not use reference implementation.
 *   
 *   The port is specified at the running time of Traffosim, or shouldn't it be pre-set for 
 *   Traffobase listener? If its set for Traffobase listener, we will not need to specify the port
 *   number for Traffosim.
 * @author Nam Nguyen
 */
public class Controller {

  private Config config;
  private String serverAddress = "127.0.0.1";
  private int port = 31000;


    
  /**
   * Sets the address of the Traffobase server. 
   * @param address Server's address.
   */
  public void setServerAddress (String address) {
    this.serverAddress = address;
  }
  
  /**
   * Sets the port of the Traffobase server.
   * @param port Server port
   */
  public void setPort(int port) {
    this.port = port;
  }
  
  /**
   * Opens a specified configuration file. 
   * 
   * @param file The configuration file to be opened.
   * @throws ConfigException If there are errors with configuration file.
   */
  public void openConfig(File file) throws ConfigException {
    config = new Config(file);
  }

  // Change to add transmission mode and sending rate handling here.
  /**
   * Sends packets to the specified host and port.
   * 
   * @throws InterruptedException If the wait between sending packets is interrupted.
   */
  public void sendPackets() throws InterruptedException {
    TraffobaseConnection connection = 
      new TraffobaseConnection(serverAddress, port);
    
    if (!connection.connect()) {
      System.err.println("Cannot connect to Traffobase server.");
      return;
    }
//    double rate = 1;
    double rate = config.getRate();
    TransmissionMode mode = config.getTransmissionMode();
//    System.out.println(mode.toString());

    List<TraffoPacket> packets = config.getPackets();
    
    if (TransmissionMode.BATCH.equals(mode)) {
      for (TraffoPacket packet : packets) {
        connection.sendPacket(packet);
        Thread.sleep((long) rate);
      }
    }
    connection.disconnect();
  }
  
  /**
   * Prints the current packets in the configuration on the screen.
   * @return Returns a string representing the configuration's current packets.
   */
  public String printPackets() {
    return config.toPrettyString();
  }
  
}
